import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {CudTableService} from '../../public/serve/cud-table/cud-table.service';
import {Service} from '../../server/server';
import { RemoveTableService } from '../../public/serve/remove-table/remove-table.service';
import {HintsService} from '../../public/serve/hints/hints.service';
import { BaseTreeComponent } from '../../public/components/base-tree/base-tree.component';
import { TreeNode } from '../../public/common/api';
import {keyword} from '../../keyword/keyword.data';
import {Pagination} from '../../public/serve/pcrudInfo';

declare var $:any;
@Component({
  selector: 'app-internal-indexed-modal-reltheme',
  templateUrl: './internal-indexed-modal-reltheme.component.html',
  styleUrls: ['./internal-indexed-modal-reltheme.component.css']
})
export class InternalIndexedModalRelthemeComponent implements OnInit {

  @Input() internalParam : any;
  public relThemeDetail:any = '';
  @Input() relThemeName:any;
  @Input() searchDataTheme: any;
  @Output() onSubmitAppView = new EventEmitter<void>();
  public productTypeCurrentId : any;
  @Input() showTitle: any;
  treeData      : TreeNode[];
  selectedData  : TreeNode[];
  listData      = [];
  currentThemeTableId = '';
  themeData = [];
  relThemeData = [];
  currentActive = -1;

  internalTablesParam = {
        taskId : "",
        productId : "",
        themeTableId : "",
        themeTableName: "",
        themeGroupId : "",
        id : "",
  };

  totalRecords: number;
  relTotalRecords: number;
  public totalItems: number;

  @Input() searchData: any;

  tableData = {};

  isSelectAll : boolean = false;
  isChose : boolean = false;

  themeTableName:any;
  public internalIndexedRelThemeEmit: any;
  public internalindexedmodelreldeleteentEmit: any;
  constructor(
    private server: Service,
    public request: CudTableService,
    private tableListService: CudTableService,
    private hintsService: HintsService,
    private removeTableService: RemoveTableService,
    private http: HttpClient
  ) { }

  ngOnInit() {
      this.tableData = {
          token         : 'b25dbd7138cf48e09941087e6d9a2e93',
          parentId  : '0',
          pageNo        : 1,
          pageSize      : 9999,
          checkStatus   : 1
      };
      this._keywordTree();

      this.internalIndexedRelThemeEmit = this.server.internalIndexedRelThemeEmit.subscribe((value: any) => {
          if (value) {
              this.searchDataTheme = '';
              this.relThemeDetail = value;
              this.relThemeName = this.relThemeDetail['themeWordsName'];
              if(this.treeData.length > 0){
                  this.currentThemeTableId = this.treeData[0]['themeTableId'];
                  this.currentActive =  this.treeData[0]['themeTableId'];
              }else{
                  this.currentActive = -1;
              }

              this._getThemeList();
              this._getRelThemeList();

          }
      });

      this.internalindexedmodelreldeleteentEmit = this.server.internalindexedmodelreldeleteentEmit.subscribe((value: any) => {
          if (value) {
              this._getThemeList();
              this._getRelThemeList();
          }
      });
  }

  ngOnDestroy() {
        this.internalIndexedRelThemeEmit ? this.internalIndexedRelThemeEmit.unsubscribe() : '';
        this.internalindexedmodelreldeleteentEmit ? this.internalindexedmodelreldeleteentEmit.unsubscribe() : '';
    }

  /**
   * 
   * 查询任务已分配的主题词表的主题词列表
   * 树状图
   */ 
  _keywordTree() {
    //已标引的主题词
    let data = this.tableData;
    this.request.postRequest( this.server.baseUrl + 'Service/ThemeWords/getThemeTablesList',data).then((res:any) => {
      
      if (res.result_code === '0000') {
        this.listData = res.result;
        this.treeData = this._processTreeData(this.listData,'themeWordsId','parentid','name');
         // 展开所有节点
         this._expandAll();
      }else{
        this.hintsService.messages(res.message,res.result_code); 
      }
      return;
    })
    .catch((err: any)=>{
      this.hintsService.messages("error","error");
      return;
    });
  }

  public getChildrenList(queryCriteria,node){
        // this.loading = true;
        let url = this.server.baseUrl + 'Service/ThemeWords/' +
            '';
        let data = queryCriteria;
        this.tableListService.postRequest(url, data).then((data: any) => {
            // this.loading = false;
            if(data.result_code == '0000') {

                node['children'] = this._toTree(data.result, node['themeTableId'], 'themeTableId','parentid','name');
                this.treeData = [...this.treeData]
                return false;
            }else {
                this.hintsService.messages(data.message, data.result_code);
            }

        }).catch();
    }

  _processTreeData(list: Array<any>, idName, parentIdName, labelName): Array<any> {
        return this._toTree(list, '0', idName,parentIdName,labelName);
  }

  _toTree(list: Array<any>, topId = '0', idName, parentIdName, labelName) {
        let idKey = idName;
        let result = [];

        for (let item of list) {

            if (item[parentIdName] == topId) {

                let children = {};
                let expandedIcon = 'fa fa-folder-open';
                let collapsedIcon = 'fa fa-folder';
                let leaf = false;

                if(item['child'] == '0'){
                    expandedIcon = '';
                    collapsedIcon = '';
                    leaf = true;
                }

                let dataArr = {
                    'data':{
                        label: item['name'],
                        data: item['themeTableId'],
                        expandedIcon: expandedIcon,
                        collapsedIcon: collapsedIcon,

                        arrchildid:item['arrchildid'],
                        arrparentid:item['arrparentid'],
                        checkStatus:item['checkStatus'],
                        createBy:item['createBy'],
                        child:item['child'],
                        name : item['name'],
                        createTime : item['createTime'],
                        status : item['status'],
                        themeGroupId:item['themeGroupId'],
                        themeTableId:item['themeTableId'],
                        themeTableCode:item['themeTableCode'],
                        parentid:item['parentid'],
                        description:item['description'],
                    },
                    'leaf': leaf,
                    'themeTableId':item['themeTableId']
                };

                result.push(dataArr);
            }
        }
        return result;
    }

  onNodeExpand(event) {

        setTimeout(() => {
            const node = event.node;
            let queryData = {};
            queryData['parentId'] = node.themeTableId;
            queryData['pageNo'] = 1;
            queryData['pageSize'] = 9999;
            this.getChildrenList(queryData,node);
        }, 100);

    }

  /**
   * 展开所有树节点
   */
  private _expandAll() {
    this.treeData.forEach(node => {
      this.expandRecursive(node, true);
    });
  }

  // 递归
  private expandRecursive(node: TreeNode, isExpand: boolean) {
    // node.expanded = isExpand;
    if (node.hasOwnProperty('childProductTypeVoList')) {
      node.children = node['childProductTypeVoList'];
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }

  //左侧主题表树点击
  themeTableSelect(val){
    if(val){
        this.currentThemeTableId = val.themeTableId
        this.currentActive = val.themeTableId;
        this._getThemeList();
    }
  }

  //根据主题词表获取未标引主题词列表
  _getThemeList(){
      let data = {
          pageNo        : this.pageNumber,
          pageSize      : this.pageSize,
          queryCriteria : this.searchDataTheme,
          themeWordsName : this.searchDataTheme,
          themeTableId  : this.internalParam['themeTableId'],
          themeWordsId  : this.relThemeDetail.themeWordsId,
          productId  : this.internalParam['productId'],
          taskId  : this.internalParam['taskId'],
          relThemeTableId  :this.currentThemeTableId
      };
      let url = this.server.baseUrl +  'Service/IdxProduct/getNoRelationThemeList';
      this.request.postRequest(url,data).then((res:any) => {
          if (res.result_code === '0000') {
              this.themeData = res.result;
              this.totalRecords = res.length;
          }else{
              this.hintsService.messages(res.message,res.result_code);
          }
          return;
      })
          .catch((err: any)=>{
              this.hintsService.messages("error","error");
              return;
          });
  }

  //根据标引主题词和表获取已关联主题词列表
  _getRelThemeList(){
        let data = {
            // pageNo        : this.pageNumber,
            // pageSize      : this.pageSize,
            pageNo        : 1,
            pageSize      : 999,
            queryCriteria : keyword.retrieval.queryCriteria,
            themeTableId  : this.internalParam['themeTableId'],
            themeWordsId  : this.relThemeDetail.themeWordsId,
            productId  : this.internalParam['productId'],
            taskId  : this.internalParam['taskId']
        };
        let url = this.server.baseUrl +  'Service/IdxProduct/getProductThemeRelationList';
        this.request.postRequest(url,data).then((res:any) => {
            if (res.result_code === '0000') {
                this.relThemeData = res.result;
                this.relTotalRecords = res.length;
            }else{
                this.hintsService.messages(res.message,res.result_code);
            }
            return;
        })
            .catch((err: any)=>{
                this.hintsService.messages("error","error");
                return;
            });
    }

  //添加关联主题词
  addRelTheme(val){
    if(val){
        let data = {
            themeTableId  : this.internalParam['themeTableId'],
            themeWordsId  : this.relThemeDetail.themeWordsId,
            themeWordsName  : this.relThemeDetail.themeWordsName,
            productId  : this.internalParam['productId'],
            taskId  : this.internalParam['taskId'],
            relThemeTableId  : val['themeTableId'],
            relThemeWordsId  : val['themeWordsId'],
            relThemeWordsNname  : val['name'],
            createBy  : this.server.getuserName()
        };
        let url = this.server.baseUrl +  'Service/IdxProduct/setProductThemeRelation';
        this.request.postRequest(url,data).then((res:any) => {
            if (res.result_code === '0000') {
                this._getThemeList();
                this._getRelThemeList();
            }
            this.hintsService.messages(res.message,res.result_code);
            return;
        })
            .catch((err: any)=>{
                this.hintsService.messages("error","error");
                return;
            });
    }
  }

    /**
     * 删除（弹窗）
     * @param info
     */
  delRelTheme(id) {
      this.removeTableService.keywordRemoveChose(true,id,1);
      $("#reltheme-delete").modal("show");
  }
  
    // 表格
    tableNumber: number = 0;
    // 当前页（默认为第一页）
    public pageNumber: number = 1;

    // 每页显示多少条数据（默认每页显示20条）
    public pageSize: number = 10;
    // id
    public id: string = '0';
    // 分页
    public pagination: Pagination;
    _pagination(pagination: Pagination) {
        this.pagination = pagination;

        this.pageNumber = this.pagination[0].pageNumber;
        this.pageSize = this.pagination[0].pageSize;
        this.id = this.pagination[0].id;

        this.tableNumber = (pagination[0].pageNumber - 1) * pagination[0].pageSize;

        this._getThemeList();
    }


  //搜索
  search() {
    this.tableData = {
      token         : 'b25dbd7138cf48e09941087e6d9a2e93',
      parentId  : '0',
      pageNo        : 1,
      pageSize      : 10,
      checkStatus   : 1
    };
    this._getThemeList();
  }
  //响应搜索
  changesearch() {
      this.search();
  }

}
